package 字符串;

import java.util.Iterator;

//https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880?tpId=295&tqId=1024725&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
public class _BM85_验证IP地址 {

	public static void main(String[] args) {
//		String ip = "172.16.254.1";
//		String ip = "172.016.254.1";
		String ip = "20EE:FGb8:85a3:0:0:8A2E:0370:7334";
		_BM85_验证IP地址 test = new _BM85_验证IP地址();
		System.out.println(test.solve(ip));
	}
	
	public String solve (String IP) {
        if(isIPv4(IP)) {
        	return "IPv4";
        }else if (isIPv6(IP)) {
			return "IPv6";
		}
        return "Neither";
    }

	private boolean isIPv4(String ip) {
		if(ip.indexOf(".") == -1) return false;
		String[] s = ip.split("\\.");
		if(s.length != 4) return false;
		for(int i =0;i<s.length;i++) {
			//不可缺省，有一个分割为零，说明两个点相连
			int len = s[i].length();
			if(len == 0) return false;
			//比较数字位数及不为零时不能有前缀零
			if(len < 0 || len > 3 || (s[i].charAt(0) =='0' && len!=1)) {
				return false;
			}
			
			//遍历每个分割字符串，必须为数字
			for(int j=0;j< s[i].length();j++) {
				if(!Character.isDigit(s[i].charAt(j))) {
					return false;
				}
			}
			int num = Integer.parseInt(s[i]);
			if(num <0 || num > 255) {
				return false;
			}
		}
		return true;
	}
	
	private boolean isIPv6(String ip) {
		if (ip.indexOf(':') == -1) {
            return false;
        }
        String[] s = ip.split(":",-1);
        //IPv6必定为8组
        if(s.length != 8) return false;
        for(int i =0;i<s.length;i++) {
        	int len = s[i].length();
        	//每个分割不能缺省，不能超过4位
        	if(len == 0 || len > 4) return false;
        	for(int j = 0;j<len;j++) {
        		//不能出现a-fA-F以外的大小写字符
        		char c = s[i].charAt(j);
        		boolean expr = (c >= '0' && c <= '9') 
        				|| (c >= 'a' && c <= 'f') 
        				|| (c >= 'A' && c <= 'F');
        		if(!expr) return false;
        	}
        }
        return true;
	}
}
